import express from 'express'
import { authenticateToken } from '../middleware/auth.js'
import db, { generateId } from '../db/database.js'

const router = express.Router()

// 所有路由需要认证
router.use(authenticateToken)

// 获取聊天消息列表
router.get('/messages', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { contextType = 'c2c_trade', contextId, page = 1, pageSize = 50 } = req.query

    if (!contextId) {
      return res.status(400).json({
        code: 400,
        message: 'contextId 参数必填',
        success: false
      })
    }

    // 验证用户是否有权限查看此聊天的消息
    // 对于C2C交易，检查用户是否是交易的参与方
    if (contextType === 'c2c_trade') {
      const trade = db.prepare('SELECT buyer_id, seller_id FROM c2c_trades WHERE trade_id = ?').get(contextId)
      if (!trade) {
        return res.status(404).json({
          code: 404,
          message: '交易不存在',
          success: false
        })
      }
      if (trade.buyer_id !== userId && trade.seller_id !== userId) {
        return res.status(403).json({
          code: 403,
          message: '无权查看此聊天',
          success: false
        })
      }
    }

    // 获取消息列表
    const offset = (parseInt(page) - 1) * parseInt(pageSize)
    const messages = db.prepare(`
      SELECT 
        m.*,
        sender.username as sender_username,
        receiver.username as receiver_username
      FROM chat_messages m
      JOIN users sender ON m.sender_id = sender.id
      JOIN users receiver ON m.receiver_id = receiver.id
      WHERE m.context_type = ? AND m.context_id = ?
      ORDER BY m.created_at ASC
      LIMIT ? OFFSET ?
    `).all(contextType, contextId, parseInt(pageSize), offset)

    // 获取总数
    const total = db.prepare(`
      SELECT COUNT(*) as total 
      FROM chat_messages 
      WHERE context_type = ? AND context_id = ?
    `).get(contextType, contextId).total

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        list: messages.map(msg => ({
          messageId: msg.message_id,
          contextType: msg.context_type,
          contextId: msg.context_id,
          senderId: msg.sender_id,
          senderUsername: msg.sender_username,
          receiverId: msg.receiver_id,
          receiverUsername: msg.receiver_username,
          content: msg.content,
          messageType: msg.message_type,
          isRead: msg.is_read === 1,
          createdAt: msg.created_at
        })),
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    })
  } catch (error) {
    next(error)
  }
})

// 发送消息（HTTP接口，主要用于历史消息同步）
router.post('/messages', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { contextType = 'c2c_trade', contextId, receiverId, content, messageType = 'text' } = req.body

    if (!contextId || !receiverId || !content) {
      return res.status(400).json({
        code: 400,
        message: 'contextId, receiverId, content 参数必填',
        success: false
      })
    }

    // 验证用户是否有权限发送消息
    if (contextType === 'c2c_trade') {
      const trade = db.prepare('SELECT buyer_id, seller_id FROM c2c_trades WHERE trade_id = ?').get(contextId)
      if (!trade) {
        return res.status(404).json({
          code: 404,
          message: '交易不存在',
          success: false
        })
      }
      if (trade.buyer_id !== userId && trade.seller_id !== userId) {
        return res.status(403).json({
          code: 403,
          message: '无权发送消息',
          success: false
        })
      }
      // 验证接收者是否是交易的另一方
      if (trade.buyer_id !== receiverId && trade.seller_id !== receiverId) {
        return res.status(400).json({
          code: 400,
          message: '接收者必须是交易的参与方',
          success: false
        })
      }
    }

    // 创建消息
    const messageId = `MSG${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`
    const id = generateId()

    db.prepare(`
      INSERT INTO chat_messages (id, message_id, context_type, context_id, sender_id, receiver_id, content, message_type)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `).run(id, messageId, contextType, contextId, userId, receiverId, content, messageType)

    const message = db.prepare(`
      SELECT 
        m.*,
        sender.username as sender_username,
        receiver.username as receiver_username
      FROM chat_messages m
      JOIN users sender ON m.sender_id = sender.id
      JOIN users receiver ON m.receiver_id = receiver.id
      WHERE m.id = ?
    `).get(id)

    res.json({
      code: 200,
      message: '发送成功',
      success: true,
      data: {
        messageId: message.message_id,
        contextType: message.context_type,
        contextId: message.context_id,
        senderId: message.sender_id,
        senderUsername: message.sender_username,
        receiverId: message.receiver_id,
        receiverUsername: message.receiver_username,
        content: message.content,
        messageType: message.message_type,
        isRead: message.is_read === 1,
        createdAt: message.created_at
      }
    })
  } catch (error) {
    next(error)
  }
})

// 标记消息为已读
router.put('/messages/:messageId/read', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { messageId } = req.params

    const message = db.prepare('SELECT * FROM chat_messages WHERE message_id = ?').get(messageId)
    if (!message) {
      return res.status(404).json({
        code: 404,
        message: '消息不存在',
        success: false
      })
    }

    // 只能标记自己接收的消息为已读
    if (message.receiver_id !== userId) {
      return res.status(403).json({
        code: 403,
        message: '无权操作',
        success: false
      })
    }

    db.prepare('UPDATE chat_messages SET is_read = 1 WHERE id = ?').run(message.id)

    res.json({
      code: 200,
      message: '标记成功',
      success: true
    })
  } catch (error) {
    next(error)
  }
})

// 标记某个上下文的所有消息为已读
router.put('/messages/read-all', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { contextType = 'c2c_trade', contextId } = req.body

    if (!contextId) {
      return res.status(400).json({
        code: 400,
        message: 'contextId 参数必填',
        success: false
      })
    }

    // 验证权限
    if (contextType === 'c2c_trade') {
      const trade = db.prepare('SELECT buyer_id, seller_id FROM c2c_trades WHERE trade_id = ?').get(contextId)
      if (!trade) {
        return res.status(404).json({
          code: 404,
          message: '交易不存在',
          success: false
        })
      }
      if (trade.buyer_id !== userId && trade.seller_id !== userId) {
        return res.status(403).json({
          code: 403,
          message: '无权操作',
          success: false
        })
      }
    }

    db.prepare(`
      UPDATE chat_messages 
      SET is_read = 1 
      WHERE context_type = ? AND context_id = ? AND receiver_id = ?
    `).run(contextType, contextId, userId)

    res.json({
      code: 200,
      message: '标记成功',
      success: true
    })
  } catch (error) {
    next(error)
  }
})

// 获取未读消息数量
router.get('/messages/unread-count', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { contextType, contextId } = req.query

    let query = 'SELECT COUNT(*) as total FROM chat_messages WHERE receiver_id = ? AND is_read = 0'
    const params = [userId]

    if (contextType) {
      query += ' AND context_type = ?'
      params.push(contextType)
    }

    if (contextId) {
      query += ' AND context_id = ?'
      params.push(contextId)
    }

    const result = db.prepare(query).get(...params)

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        unreadCount: result.total
      }
    })
  } catch (error) {
    next(error)
  }
})

export default router






